import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./userStore";
import { insertCartAPI, findNewCartListAPI, delCartAPI } from "@/apis/cart";


export const useCartStore = defineStore('cart', () => {
  const user = useUserStore()
  const isLogin = computed(() => user.userInfo.token)

  const cartList = ref([])

  // 获取购物车列表
  const updataNewList = async () => {
    const res = await findNewCartListAPI()
    cartList.value = res.result
  }

  // 加购物车
  const addCartList = async (goods) => {
    const { skuId, count } = goods
    if (isLogin.value) {
      // 有token 登录状态
      // 调用加入购物车接口
      await insertCartAPI({ skuId, count })
      // 调用获取购物车列表接口
      // 用接口购物车列表覆盖本地购物车列表
      updataNewList()
    } else {
      // 没token 非登录
      //本地购物车加购物车操作
      // 同样的添加过 原count++
      // 没有加过 push进数组
      // 思路：判断传过来的goods中的skuid能不能在cartList找到
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      if (item) {
        // 同样的添加过 原count++
        item.count++
      } else {
        //没找到  push
        cartList.value.push(goods)
      }
    }

  }

  // 删除某个购物车项
  const delCart = async (skuid) => {
    if (isLogin.value) {
      await delCartAPI([skuid])
      updataNewList()
    } else {
      const idx = cartList.value.findIndex((item) => skuid === item.skuId)
      cartList.value.splice(idx, 1)
    }
  }

  // 清空购物车
  const clearCartList = () => {
    cartList.value = []
  }

  // 列表购物车单选功能
  const singleCheck = (skuid, selected) => {
    const item = cartList.value.find((item) => skuid === item.skuId)
    item.selected = selected
  }

  // 列表购物车全选功能
  const allCheck = (selected) => {
    cartList.value.forEach((item) => {
      item.selected = selected
    })
  }



  // 购物车总计
  // 1.总数量
  const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
  // 2.总价
  const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))

  // 列表购物车全选功能 判断是否全选
  const isAll = computed(() => cartList.value.every((item) => item.selected === true))

  // 列表购物车 已选择商品数量
  // cartList.value.filter(item => item.selected)会返回一个筛选过的新数组
  // 对新数组.reduce((a, c) => a + c.count, 0)
  const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
  // 列表购物车 已选择商品总价
  const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))


  return {
    cartList,
    allCount,
    allPrice,
    addCartList,
    delCart,
    singleCheck,
    isAll,
    allCheck,
    selectedCount,
    selectedPrice,
    clearCartList,
    updataNewList,

  }
}, {
  persist: true,
},)